package com.hs.srm.api.modules.requisition.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hs.srm.admin.common.util.OANoticeUtil;
import com.hs.srm.admin.modules.requisition.entity.*;
import com.hs.srm.admin.modules.requisition.service.NproPurchRequestHeaderService;
import com.hs.srm.admin.modules.requisition.service.NproPurchRequestItemService;
import com.hs.srm.admin.modules.requisition.service.SamplePurchRequestHeaderService;
import com.hs.srm.admin.modules.requisition.service.SamplePurchRequestItemService;
import com.hs.srm.base.common.utils.DictDataUtil;
import com.hs.srm.common.utils.R;
import com.landray.kmss.km.review.webservice.Exception_Exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sunnykid.file.DirectoryOperator;
import sunnykid.text.SunnykidText;
import sunnykid.web.http.HttpClient;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import static sunnykid.util.HtmlUtils.getDocumentFromURL;

/**
 * @date 2019年2月14日
 * 样品采购申请头信息
 */
@Controller
@RequestMapping("/api/samplePurchRequest")
@EnableAutoConfiguration
public class SamplePurchRequestApi {

    private Logger logger = LoggerFactory.getLogger(SamplePurchRequestApi.class);

    // 注入业务层
    @Autowired
    private SamplePurchRequestHeaderService samplePurchRequestHeaderService;

    @Autowired
    private SamplePurchRequestItemService samplePurchRequestItemService;

    @Value("${hssrm.file-upload-path}")
    protected String fileUploadPath;

    /**
     * OA传递采购申请数据的接口（不包含附件文件的JSON数据）
     * http://168.102.5.113:8085/hssrm/api/nproPurchRequest/dataFromOA
     */
    @Transactional
    @RequestMapping(value = "/dataFromOA", method = RequestMethod.POST)
    @ResponseBody
    public R dataFromOA(String data) throws Exception_Exception {
        logger.info("样品申请单同步成功!" + data);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        // gson.newBuilder();
        SamplePurchRequestModel model = gson.fromJson(data, SamplePurchRequestModel.class);
        // 得到采购申请头
        SamplePurchRequestHeaderEntity sampleHeader = model.getSamplePurchRequestHeaderEntity();
        // 得到采购行项目
        List<SamplePurchRequestItemEntity> nproPurchRequestItemlist = model.getNproPurchRequestItemlist();
        if (sampleHeader != null && nproPurchRequestItemlist != null
                && nproPurchRequestItemlist.size() > 0) {
            sampleHeader.setPkId(SunnykidText.getUUID());
            sampleHeader.setGoodsStatus(-2);
            sampleHeader.setSrmReceiveDate(new Date());
            //SRM收到请购单时间
            sampleHeader.setSrmReceiveDate(new Date());
            for (SamplePurchRequestItemEntity samplePurchRequestItemEntity : nproPurchRequestItemlist) {
                samplePurchRequestItemEntity.setPkId(SunnykidText.getUUID());
                samplePurchRequestItemEntity.setGoodsStatus(-2);
                samplePurchRequestItemEntity.setItemType("NPRO");
                samplePurchRequestItemEntity.setMeasureUnit(DictDataUtil.txtToVal(samplePurchRequestItemEntity.getMeasureUnit(), DictDataUtil.DictType.JLDW));
                //A:固定资产,F:在建工程，不需要成本中心
                if (!samplePurchRequestItemEntity.getSubjectCategory().equals("K")) {
                    samplePurchRequestItemEntity.setCostCenter(null);
                }
            }
            try {
                this.samplePurchRequestHeaderService.insert(sampleHeader);
                this.samplePurchRequestItemService.insertBatch(nproPurchRequestItemlist);
            } catch (Exception e) {
                //日志记录传输数据
                LoggerFactory.getLogger(this.getClass()).error(data);

                //出现异常，调用OA接口，通知下单人
                OANoticeUtil.sendMsg(sampleHeader.getOAccount(), "您申请的 " + nproPurchRequestItemlist.get(0).getMaterialDesc() + " 出现异常，数据没有传到SRM，请联系管理员!", "请购申请异常通知", true);
                //抛出异常，让SRM日志记录，后期排查原因
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
        return R.ok("接收到来自OA的数据：" + data);
    }

    /**
     * OA传递采购申请附件文件
     * http://168.102.5.113:8085/hssrm/api/nproPurchRequest/fileFromOA
     */
    @RequestMapping(value = "/fileFromOA", method = RequestMethod.POST)
    @ResponseBody
    public R fileFromOA(MultipartHttpServletRequest request, String fileName) {
        String uploadPath = this.fileUploadPath + "/samplePurch_att/";
        File uploadDir = new File(uploadPath);
        // 如果没有这个目录，创建一个
        if (!DirectoryOperator.isExistingDirectory(uploadDir)) {
            DirectoryOperator.makeDirectory(uploadDir);
        }
        Map<String, MultipartFile> fileMap = request.getFileMap();
        for (Entry<String, MultipartFile> e : fileMap.entrySet()) {
            try {
                // 把文件移动到这个目录里
                e.getValue().transferTo(new File(uploadPath + e.getValue().getOriginalFilename()));
            } catch (Exception ex) {
                ex.printStackTrace();
                return R.error();
            }
        }
        int c = fileMap.size();
        return R.ok("接收到来自OA的数据id：" + fileName + "，文件：" + c + "个");
    }

    // /**
    // * 发送数据表单
    // * @param JSONString String 请购记录的JSON字符串
    // * @return Response
    // */
    // public static Response sendJSON(String JSONString) {
    // HttpClient client = new HttpClient("http://168.254.0.135:8085/hssrm/api/nproPurchRequest/dataFromOA");
    // try {
    // Response response = client.post(new Parameter("data", JSONString));
    // return response;
    // } catch(HttpException ex) {
    // System.err.println("========出错了===========");
    // ex.printStackTrace();
    // return null;
    // }
    // }
    //
    // /**
    // * 发送文件表单
    // * @param dataId String 数据记录的id
    // * @param files File[] 传输的文件（多个）
    // * @return Response
    // */
    // public static Response sendFile(String dataId, File... files) {
    // HttpClient client = new HttpClient("http://168.102.5.113:8085/hssrm/api/nproPurchRequest/fileFromOA");
    // Parameter param = new Parameter("dataId", dataId);
    // try {
    // Response response = client.upload(files, false, param);
    // return response;
    // } catch(HttpException ex) {
    // System.err.println("========出错了===========");
    // ex.printStackTrace();
    // return null;
    // }
    // }

    // {"nproPurchRequestHeaderEntity":{"pkId":"169e19ee009f3e97d30c9e5414aaaa86","purchRequestStaff":"异常管理员","purchRequestDept":"软件处","purchRequestCode":"","purchRequestType":"","costCenter":"1000021002","purchGroup":"200","totalPrice":121,"creationDate":"2019-04-03"},"nproPurchRequestItemlist":[{"purchRequestCode":"","purchRequestItemCode":0,"materialGroup":"9039","materialDesc":"111","applier":"异常管理员","costCenter":"1000021002","applyQty":11,"measureUnit":"%   ","taxPrice":11,"count":121,"requestDate":"2019-04-03","attachment":"新建文本文档.txt","purpose":"测试"}]}

    public static void main(String[] args) {
//		String json = "{\"nproPurchRequestHeaderEntity\":{\"pkId\":\"169e19ee009f3e97d30c9e5414aaaa86\",\"purchRequestStaff\":\"异常管理员\",\"purchRequestDept\":\"软件处\",\"purchRequestCode\":\"\",\"purchRequestType\":\"\",\"costCenter\":\"1000021002\",\"purchGroup\":\"200\",\"totalPrice\":121,\"creationDate\":\"2019-04-03\"},\"nproPurchRequestItemlist\":[{\"purchRequestCode\":\"\",\"purchRequestItemCode\":0,\"materialGroup\":\"9039\",\"materialDesc\":\"111\",\"applier\":\"异常管理员\",\"costCenter\":\"1000021002\",\"applyQty\":11,\"measureUnit\":\"%\",\"taxPrice\":11,\"count\":121,\"requestDate\":\"2019-04-03\",\"attachment\":\"新建文本文档.txt\",\"purpose\":\"测试\"}]}";
//		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
//		// gson.newBuilder();
//		ProPurchRequestModel model = gson.fromJson(json, ProPurchRequestModel.class);
//		System.out.println(model.getNproPurchRequestHeaderEntity().getPkId());
//		System.out.println(model.getNproPurchRequestItemlist().size());
//		System.out.println(model.getNproPurchRequestItemlist().get(0).getRequestDate());

        HttpClient c = new HttpClient("http://www.baidu.com");

        try {
            System.out.println(getDocumentFromURL("http://www.baidu.com").title());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
